package com.quan.generator.web.controller;

import com.quan.commons.core.bean.R;
import com.quan.commons.core.biz.support.MyBaseController;
import com.quan.commons.core.utils.PageUtils;
import com.quan.generator.GeneratorVo;
import com.quan.generator.service.MySQLGeneratorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 代码生成
 */
@Slf4j
@RestController
@RequestMapping("/generator")
public class MySQLGeneratorController extends MyBaseController {

    @Autowired
    private MySQLGeneratorService service;

    @RequestMapping("index")
    public String index() {
        return "index";
    }

    /**
     * 查询数据库
     * @param params
     * @return
     */
    @GetMapping(value = "database")
    public R database(@RequestParam Map<String, Object> params) {
        return R.ok().put("data", this.service.selectDatabase(params));
    }

    /**
     * 数据库表列表
     * @param params
     * @return
     */
    @GetMapping(value = "tables")
    public R tables(@RequestParam Map<String, Object> params) {
        return R.ok().put("data", this.service.selectTables(new PageUtils(request), params));
    }

    /**
     * 下载生成的代码
     * @param vo
     * @throws IOException
     */
    @PostMapping("code")
    public void code(@RequestBody GeneratorVo vo) throws IOException {
        byte[] data = this.service.generatorCode(vo.getDatabase(), vo.getPackageName(), vo.getModuleName(), vo.getTables());

        if(null != data && data.length > 0) {
            String filename = "代码生成" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".zip";

            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=UTF-8");
            // 设置暴露可以访问的头部信息，如果返回的filename想要被访问到
            // 通过Access-Control-Expose-Headers 指定暴露的属性 filename
            response.setHeader("Access-Control-Expose-Headers", "filename");
            response.setHeader("filename", java.net.URLEncoder.encode(filename, "UTF-8"));
            response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            ServletOutputStream outStream = null;
            try {
                outStream = response.getOutputStream();
                //data.write(outStream);
                outStream.write(data);
                outStream.flush();
            } finally {
                outStream.close();
            }
        } else {
            log.error("代码生成数据库为空...");
        }
    }

}
